var toPage;
$(function () {
    loadCompanyList();
    loadTimeRule();
})

$("#page").paging({
    pageNo: 1,
    totalPage: 1,
    totalSize: 1,
    callback: function (num) {
    }
});
laydate.render({
    elem: '#validationCustom11',
    type: 'time',
    trigger: 'click'
});
laydate.render({
    elem: '#validationCustom12',
    type: 'time',
    trigger: 'click'
});
function companyChange(val){
    $('#company-list-vld').val(val);
    $('#eIdT_id').val(val);
    $('#timeRule_List').empty();
    loadRule(val);
}

/*添加*/
function addInfo() {
    $('#form1')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    $('#modal_title').text('添加时间规则');
    $('#timeRule_List').empty();
    $("#company-list").removeAttr("disabled");
    loadRule($("#company-list").val());

    $('#addInfoModal').modal();
    //注意，选择企业后，若企业已有时间规则，应读取过来
}

/*修改信息*/
function editInfo(e) {
    //$('#timeRule_List').empty();
    $('#modal_title').text('修改时间规则');
    $('#methodType_id').val(1);
    $('#eIdT_id').val(e);
    $('#company-list-vld').val(e);
    $('#company-list').selectivity('val', e);
    $('#company-list').attr('disabled', 'disabled');
    $('#addInfoModal').modal();
    //修改中，企业名称禁止修改，仅修改其时间规则
}

/* 添加规则相关事件 */

//点击添加规则
function addRuler() {
    if (!$('#company-list').selectivity('val')) {
        myAlert("提示", "请先选择企业");
        return;
    }
    $('#add_ruler_wrapper').slideDown(0);
    $('#add_ruler_wrapper')[0].reset();//清空表单
}

//确认添加
function confirmSelection() {
    // $('#timeRule_List').empty();
    //获取重复内容
    var value = [];
    $.each($('input:checkbox[name=weekList]:checked'), function () {
        value.push($(this).val());
    });
    var value_str = value.join('、');
    if(isNull($('#validationCustom11').val())||isNull($('#validationCustom12').val())){
        myAlert("提示","开始时间和结束时间为必填项");
        return;
    }
    if(isNull(value_str)){
        myAlert("提示","重复周期为必选项");
        return;
    }
    let startTime = $('#validationCustom11').val();
    let endTime = $('#validationCustom12').val();
    let cycle = value.join('、');
    buildTimeRule($('#timeRule_List'), startTime, endTime, cycle);
    $('#add_ruler_wrapper').slideUp(0);
}

//取消
function cancelSelection() {
    $('#add_ruler_wrapper').slideUp(0);
}

function deleteBy(e) {
    e.parentNode.remove();
}

function loadTimeRule(_pageIndex) {
    $('#addInfoModal').modal('hide');
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage=pageIndex;
    getJson('/timeRule/getTimeRuleByParam', {
        searchValue: searchValue,
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {
        if (data['code'] == 200) {
            let payload = data['payload'];
            $("#page").paging({
                pageNo: pageIndex,
                totalPage: payload['pages'],
                totalSize: payload['total'],
                callback: function (num) {
                    getEnterpriseList(num);
                }
            });
            let list = payload['data'];
            let order = 1 + 10 * (pageIndex - 1);
            for (let item of list) {
                item['order'] = order++;
            }
            buildTable($('#time_List'), title, label, list, function (td, label, item) {
                switch (label) {
                    case 'rule':
                        for (let rule of item['timeRuleList']) {
                            rule['cycle'] = setCycle(rule).join('、');
                            createElement('div', td, '工作时间：' + rule['startTime'] + '-' + rule['endTime'] +
                                '；重复： ' + rule['cycle'], null);
                        }
                        break;
                    case 'opera':
                        let btnEdit = createElement('a', td, null, null);
                        $(btnEdit).addClass('font-p24');
                        $(btnEdit).attr('href', 'javascript: void(0);');
                        $(btnEdit).click(function () {
                            editInfo(item['id']);
                        });
                        let aEdit = createElement('i', btnEdit, null, null);
                        $(aEdit).addClass('iconfont').addClass('icon-bianji-');

                        let btnDel = createElement('a', td, null, null);
                        $(btnDel).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                        $(btnDel).attr('href', 'javascript: void(0);');
                        $(btnDel).click(function () {
                            deleteInfo(item['id']);
                        });
                        let aDel = createElement('i', btnDel, null, null);
                        $(aDel).addClass('iconfont').addClass('icon-shanchuicon');
                        break;
                }
            })
        } else {
            myAlert('提示', data['message']);
        }
    hideLoading();
    });
}

/*保存时间规则*/
function submitData() {
    if (!$('#company-list').selectivity('val')) {
        myAlert("提示", "请先选择企业");
        return;
    }
    let params = $('#form1').serialize();
    $.ajax({
        url: "../timeRule/saveOrUpdateTimeRule",
        type: 'POST',
        data: params,
        datatype: 'json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('token', sessionStorage.getItem("token"));
        },
        success: function (data) {
            if (data.code == 200) {
                myAlert("提示", "保存成功", function () {
                    loadTimeRule(toPage);
                    return;
                })
            }
            myAlert("提示", "保存失败")
        },
        error: function (data) {
            myAlert("提示", "保存失败")
        }
    });
}

function deleteInfo(e) {
    myConfirm("提示", "您是否要删除此条规则", function (res) {
        if (res) {
            getJson("/timeRule/deleteInfo",{"id": e},'GET',function (result) {
                if (result.code == 200) {
                    myAlert("提示", "删除成功", function () {
                        loadTimeRule(toPage);
                        return;
                    })
                }
                myAlert("提示", "删除失败")
            })
        }
    })
}
function loadRule(id) {
    let timeRule = $('#timeRule_List');
    timeRule.empty();
    if (id) {
        getJson( '/timeRule/getTimeRuleByParam', {id: id}, 'GET', function (data) {
            if (data['code'] == 200) {
                let ruleList = data['payload']['data'];
                if (ruleList.length > 0) {
                    for (let item of ruleList[0]['timeRuleList']) {
                        item['cycle'] = setCycle(item).join('、');
                        buildTimeRule(timeRule, item['startTime'], item['endTime'], item['cycle'])
                    }
                }
            } else {
                myAlert("提示", data['message']);
            }
        })
    }
}
function buildTimeRule(e, startTime, endTime, cycle) {
    let box_out = createElement('div', e, null, null);
    $(box_out).addClass('d-flex').addClass('align-items-center').addClass('mb-2');
    let box_in = createElement('div', box_out, null, null);
    $(box_in).addClass('time-ruler').addClass('flex-1');
    let div_time = createElement('div', box_in, '工作时间：' + startTime + '-' + endTime, null);
    let div_cycle = createElement('div', box_in, '重复：' + cycle, null);
    let input_beginTime = createElement('input', box_in, null, startTime);
    $(input_beginTime).attr('name', 'beginTime');
    $(input_beginTime).attr('type', 'hidden');
    let input_endTime = createElement('input', box_in, null, endTime);
    $(input_endTime).attr('name', 'endTime');
    $(input_endTime).attr('type', 'hidden');
    let input_cycle = createElement('input', box_in, null, cycle);
    $(input_cycle).attr('name', 'cycle');
    $(input_cycle).attr('type', 'hidden');
    let aEdit = createElement('a', box_out, null, null);
    $(aEdit).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
    $(aEdit).attr('href', 'javascript: void(0);');
    $(aEdit).click(function () {
        deleteBy(this);
    });
    let iEdit = createElement('i', aEdit, null, null);
    $(iEdit).addClass('iconfont').addClass('icon-shanchuicon');
}
function setCycle(rule) {
    let cycle = [];
    if (rule['monday']) {
        cycle.push("周一");
    }
    if (rule['tuesday']) {
        cycle.push('周二');
    }
    if (rule['wednesday']) {
        cycle.push('周三');
    }
    if (rule['thursday']) {
        cycle.push('周四');
    }
    if (rule['friday']) {
        cycle.push('周五');
    }
    if (rule['saturday']) {
        cycle.push('周六');
    }
    if (rule['sunday']) {
        cycle.push('周日')
    }
    return cycle;
}